/*
Merge marital histories and fertility events to cleaned psid data
also contains move-in histories in case we want to look at that later!

Author: GA
Last Modified 7/19/2019
*/

clear all

//get parent ID values
do "$dofiles/PSID/00_psid_fam_readin_v1"
do "$dofiles/PSID/00_psid_fam_format_v1"

gen uniqid = ER30001*1000 + ER30002 //unique identifier

//child birth date variables
ren ER32024 birth_year_1 //first
ren ER32028 birth_year_4 //fourth youngest
ren ER32030 birth_year_3 //third youngest
ren ER32032 birth_year_2 //second youngest
ren ER32026 birth_year_5 //youngest

//rename marital status variable
ds uniqid birth*, not

***********big renaming loop; use variable labels
ds uniqid, not
foreach var in `r(varlist)'{
	
	//fetch label
	local lab: variable label `var'
	
	//get year for individual files
	local num = word("`lab'", -1)
	
	//skip variables inconvenient labels for now
	if length("`num'")!=2 | "`var'" == "V4373" {
		continue
	}	
	
	if `num'<20{ //2000s variable
		local year = 2000 + `num'
	}
	if `num'>20{ //1900s variable
		local year = 1900 + `num'
	}
	
	****rename according to label contents
	//age
	if strpos("`lab'", "MARR") |  strpos("`lab'", "MARITAL"){
		ren `var' marst`year'
	}
}

keep uniqid birth* marst* //keep fertility and marriage dates
reshape long marst, i(uniqid) j(year)
tempfile fam
save `fam'

//merge on to intermediate psid file
use "$scratch/psid_long_parentloc", clear
merge 1:1 uniqid year using `fam', keep(match) nogen
replace marst = 1 if marst>0 //0 indicates non-married, 1 indicates married

//dummy indicating birth of a child in given year
gen birth = 0
replace birth = 1 if year == birth_year_1 | year == birth_year_2 |  year == birth_year_3 |  year == birth_year_4 |  year == birth_year_5 
drop birth_year*

//fertility range variable
sort uniqid year
gen fertility_range = 0
replace fertility_range = 1 if birth
replace fertility_range = 1 if birth[_n+1] == 1 & uniqid[_n] == uniqid[_n+1]
replace fertility_range = 1 if birth[_n-1] == 1 & uniqid[_n] == uniqid[_n-1]
compress
save "$scratch/psid_master", replace





//end of do-file